<template>
  <!-- 初始化添加页面 -->
  <el-dialog
    v-dialogDrag
    append-to-body
    :lock-scroll="false"
    :title="initTitle"
    :visible.sync="initVisible"
    class="dialogStyleMiddle"
    :before-close="cancel"
  >
    <div style="text-align:left">
      <el-form
        v-if="initVisible"
        ref="initEnterpriseForm"
        :model="dialogFormData"
        :rules="initRules"
        label-width="80px"
      >
        <el-row>
          <el-col :span="24"><div class="grid-content bg-purple">企业信息</div></el-col>
        </el-row>
        <el-row>
          <el-col :span="22">
            <el-form-item label="企业名称" prop="deptName">
              {{ dialogFormData.enterprise.name }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24"><div class="grid-content bg-purple">部门管理员角色</div></el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="角色名称" prop="deptRoleName">
              {{ dialogFormData.deptRole.roleName }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限字符" prop="deptRoleKey">
              {{ dialogFormData.deptRole.roleKey }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24"><div class="grid-content bg-purple">分公司管理员角色信息</div></el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="角色名称" prop="roleName">
              {{ dialogFormData.role.roleName }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限字符" prop="roleKey">
              {{ dialogFormData.role.roleKey }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24"><div class="grid-content bg-purple">管理员信息</div></el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名称">{{ dialogFormData.sysUser.userName }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="登录账号">{{ dialogFormData.sysUser.loginName }}</el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="22">
            <el-form-item label="套餐选择" prop="tempId">
              {{ dialogFormData.sysCompanyTemp.name }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24"><div class="grid-content bg-purple">数据权限</div></el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="菜单权限" prop="menuIds" class="el-tree-wrap">
              <p class="all-expand">
                <span v-if="AddExpand" @click="unFoldAll()"><i class="el-icon-caret-bottom" />全部展开</span>
                <span v-else @click="closeAll()"><i class="el-icon-caret-top" />全部关闭</span>
              </p>
              <div>
                <el-tree
                  v-if="openOrNot"
                  ref="menu"
                  :data="menuOptions"
                  show-checkbox
                  node-key="id"
                  empty-text="加载中，请稍后"
                  :props="defaultProps"
                  :default-expand-all="defaultExpand"
                  :highlight-current="true"
                  :render-content="renderContent"
                  @check="handleChange"
                />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!--    <span slot="footer" class="dialog-footer">-->
    <!--      <el-button type="primary" size="medium" @click="cancel">关 闭</el-button>-->
    <!--    </span>-->
  </el-dialog>
</template>

<script>
// getMenuDept, getDeptMenuByCompTempId,
import { selectByIdAndSubCompanyDept } from '@/api/system/dept'
import { selectTreeById } from '@/api/enterprise/company-temp'
import { selectTreeMenuAll } from '@/api/system-tool/menu'
export default {
  data() {
    return {
      openOrNot: true,
      defaultExpand: false,
      // 选中的菜单树数据
      treeSelected: [],
      // 树是否全部展开
      AddExpand: true,
      // 模板名称
      templateOptiom: [],
      // 初始化内容标题
      initTitle: '',
      initVisible: false,
      // 对话框表单数据
      dialogFormData: {
        deptRole: {},
        enterprise: {},
        enterpriseId: '',
        menu: [],
        role: {},
        subCompany: '',
        sysDept: {},
        sysDeptEncodingRule: {},
        sysUser: {},
        sysCompanyTemp: {}
      },
      initEnterpriseNew: {
        // 企业id
        enterpriseId: '',
        // 分公司id
        subCompany: '',
        // 部门id
        deptId: '',
        // 部门名称
        deptName: '',
        // 部门管理员名称
        deptRoleName: '',
        // 权限字符
        deptRoleKey: '',
        roleName: '',
        roleKey: '',
        userName: '',
        loginName: '',
        password: '',

        tempId: '',
        menuIds: []
      },
      initRules: {
        userName: [
          { required: true, message: '用户名称不能为空', trigger: 'blur' }
        ],
        loginName: [
          { required: true, message: '登录账号不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '用户密码不能为空', trigger: 'blur' }
        ],
        deptRoleName: [{ required: true, message: '必填', trigger: 'blur' }],
        deptRoleKey: [{ required: true, message: '必填', trigger: 'blur' }],
        roleName: [{ required: true, message: '必填', trigger: 'blur' }],
        roleKey: [{ required: true, message: '必填', trigger: 'blur' }]
      },
      // 树形菜单数据
      menuOptions: [],
      // 加载树形菜单结构
      defaultProps: {
        children: 'children',
        label: 'label',
        disabled: this.disabledFn
      }
    }
  },
  methods: {
    // 菜单树节点加载 设置菜单后面是否显示“数据权限”字样
    renderContent(h, { node, data, checked, store }) {
      // 判断菜单类型
      const menuType = data.menuType
      // 判断节点是否选中
      var isNodeCheck = false
      /** 当节点是选中状态时显示数据权限
       * 当节点是半选中状态时也显示数据权限
       */
      if (node.checked) {
        isNodeCheck = true
      } else {
        /** 获取次节点下面的子节点
         * 当子节点其中也有选择状态时设置isNodeCheck = true
         * 并且跳出循环
         */
        const childNodes = node.childNodes
        for (var i = 0; i < childNodes.length; i++) {
          if (childNodes[i].checked) {
            isNodeCheck = true
            break
          }
        }
      }
      /**
       * 当菜单类型为菜单（C）时 并且 次菜单是选中状态或者半选中状态
       * 则显示“数据权限”字样
       */
      if (menuType === 'C' && isNodeCheck) {
        return (
          <span class='custom-tree-node'>
            <span>{node.label}</span>
            <span style='margin-left:20px'>
              <el-button
                size='mini'
                type='text'
                on-click={() => this.append(data, event)}
              >
                数据权限
              </el-button>
            </span>
          </span>
        )
      } else {
        return (
          <span class='custom-tree-node'>
            <span>{node.label}</span>
          </span>
        )
      }
    },
    // 当复选框选中状态改变时
    handleChange(data, nodefunction) {
      var _this = this
      // 定义变量用于判断当前节点有没有选择
      var isMenuId = true
      // 当天节点改变状态的值
      var menuId = data.menuId
      // 获取数组中被选中节点的值
      var checkedKeys = nodefunction.checkedKeys
      // 当前节点是选中状态标识设置为false
      for (var i = 0; i < checkedKeys.length; i++) {
        if (menuId === checkedKeys[i]) {
          isMenuId = false
        }
      }
      // 默认数据权限
      const defauleDataScopList = _this.defauleDataScopList
      // isMenuId 为 true时 表示该节点没有被选中
      if (isMenuId && data.menuType === 'C') {
        // 当前节点没有被选中,遍历树 把该节点的数据权限设为默认数据权限
        _this.changeMenuOptions(menuId, defauleDataScopList)
      } else if (isMenuId && data.menuType === 'M') {
        // 当目录节点没有被选中, 遍历树下面的菜单节点，设置为默认数据权限
        const dataMenuIds = _this.getMenuIdFilter().filter(data)
        for (var j = 0; j < dataMenuIds.length; j++) {
          _this.changeMenuOptions(dataMenuIds[j], defauleDataScopList)
        }
      } else if (isMenuId && data.menuType === 'F') {
        /* 当前节点没有选中 ，且节点是“按钮类型”,判断该节点的父节点是否是半选状态，
         * 父节点不是半选状态 且父节点是“菜单类型” 设置 父节点的数据权限为默认数据权限
         */
        // 获取该节点的父节点
        const dataParentId = data.parentId
        const halfCheckedKeys = nodefunction.halfCheckedKeys
        // 定义变量记录父节点是否是半选状态
        var isParentIdHalf = true
        for (var K = 0; K < halfCheckedKeys.length; K++) {
          if (dataParentId === halfCheckedKeys[K]) {
            // 当父节点是半选状态则 改为false
            isParentIdHalf = false
          }
        }
        if (isParentIdHalf) {
          // 父节点没有被选中,遍历树 把该节点的数据权限设为默认数据权限
          _this.changeMenuOptions(dataParentId, defauleDataScopList)
        }
      }
    },
    // 全部展开
    unFoldAll() {
      console.log(this.$refs.menu)
      this.treeSelected = this.$refs.menu.getCheckedKeys().concat(this.$refs.menu.getHalfCheckedKeys())
      this.AddExpand = false
      this.defaultExpand = true
      this.openOrNot = false
      setTimeout(() => {
        this.openOrNot = true
        this.$nextTick(() => {
          this.$refs.menu.setCheckedKeys(this.treeSelected)
        })
      }, 10)
    },
    // 全部关闭
    closeAll() {
      console.log(this.$refs.menu)
      this.treeSelected = this.$refs.menu.getCheckedKeys().concat(this.$refs.menu.getHalfCheckedKeys())
      this.AddExpand = true
      this.defaultExpand = false
      this.openOrNot = false
      setTimeout(() => {
        this.openOrNot = true
        this.$nextTick(() => {
          this.$refs.menu.setCheckedKeys(this.treeSelected)
        })
      }, 10)
    },
    // 初始化添加页面
    addFrom(enterpriseId, deptName, subCompany) {
      this.initVisible = true
      this.empetyInitEnterprise()
      this.getMenuTreeData()
      this.initTitle = '分公司初始化'
      this.initialize(subCompany)
    },
    initialize(subCompanyId) {
      this.resetForm('dialogForm')
      selectByIdAndSubCompanyDept(subCompanyId).then(resp => {
        if (resp) {
          console.log(resp.data.deptRole)
          this.$refs.menu.setCheckedKeys([])
          this.dialogFormData.deptRole = { ...resp.data.deptRole }
          this.dialogFormData.enterprise = resp.data.enterprise
          this.dialogFormData.enterpriseId = resp.data.enterpriseId
          // this.dialogFormData.menu = resp.data.menu
          this.dialogFormData.role = resp.data.role
          this.dialogFormData.subCompany = resp.data.subCompany
          this.dialogFormData.sysDept = resp.data.sysDept
          this.dialogFormData.sysDeptEncodingRule = resp.data.sysDeptEncodingRule
          this.dialogFormData.sysUser = resp.data.sysUser
          this.dialogFormData.sysCompanyTemp = resp.data.sysCompanyTemps[0]
          // this.$refs.menu.setCheckedKeys(resp.data.menu)
          this.selectMenuIdsbyId(resp.data.sysCompanyTemps[0].id)
        }
      })
      // this.getMenuTreeData()
    },
    // 根据企业套餐id查询菜单树menuIds[]
    selectMenuIdsbyId(id) {
      selectTreeById(id).then(resp => {
        if (resp) {
          var menuIds = resp.data
          this.$refs.menu.setCheckedKeys(menuIds)
        }
      })
    },
    // 树形菜单加载
    getMenuTreeData() {
      const _this = this
      selectTreeMenuAll().then(resp => {
        if (resp) {
          _this.menuOptions = resp.data
        }
      })
    },
    // 菜单树禁用
    disabledFn(data, node) {
      if (data !== null) {
        // 根据自己的节点数据条件设置判断，我只提供了个参考
        return true
      } else {
        return false
      }
    },
    // 清空初始化表单
    empetyInitEnterprise() {
      this.initEnterprise = {
        // 企业id
        enterpriseId: '',
        // 分公司id
        subCompany: '',
        // 部门id
        // deptId: "",
        // 部门名称
        deptName: '',
        // 部门管理员名称
        deptRoleName: '',
        // 权限字符
        deptRoleKey: '',
        roleName: '管理员角色',
        roleKey: 'admin',
        userName: '超级管理员',
        loginName: '',
        password: '111111',
        tempId: '',
        menuIds: []
      }
      this.resetForm('initEnterpriseForm')
    },
    // 部门编码改变时改变部门编码长度字段
    changRuleLength(val) {
      if (val != null && val !== '') {
        this.initEnterprise.ruleLength = val.length
      }
    },

    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      const checkedKeys = this.$refs.menu.getHalfCheckedKeys()
      // 半选中的菜单节点
      const halfCheckedKeys = this.$refs.menu.getCheckedKeys()
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },
    // 弹框取消按钮
    cancel() {
      this.initVisible = false
      this.empetyInitEnterprise()
    }

  }
}
</script>
<style scoped>
.el-checkbox__input.is-disabled.is-checked .el-checkbox__inner {
  background-color: #409eff;
  border-color: #dcdfe6;
}
.el-checkbox__input.is-disabled.is-checked .el-checkbox__inner::after {
  border-color: #4068ff;
}
</style>
